package org.thanos.bacnet.sero.warp;

import java.time.Clock;
import java.util.concurrent.TimeUnit;

public class WarpUtils {
    public WarpUtils() {
    }

    public static void wait(Clock clock, Object o, long timeout, TimeUnit timeUnit) throws InterruptedException {
        if (clock instanceof WarpClock warpClock) {
            TimeoutFuture<?> future = warpClock.setTimeout(() -> {
                synchronized(o) {
                    o.notify();
                }
            }, timeout, timeUnit);

            try {
                synchronized(o) {
                    o.wait();
                }
            } finally {
                future.cancel();
            }
        } else {
            o.wait(timeUnit.toMillis(timeout));
        }

    }

    public static void sleep(Clock clock, long timeout, TimeUnit timeUnit) throws InterruptedException {
        if (clock instanceof WarpClock warpClock) {
            Object o = new Object();
            TimeoutFuture<?> future = warpClock.setTimeout(() -> {
                synchronized(o) {
                    o.notify();
                }
            }, timeout, timeUnit);

            try {
                synchronized(o) {
                    o.wait();
                }
            } finally {
                future.cancel();
            }
        } else {
            Thread.sleep(timeUnit.toMillis(timeout));
        }

    }
}

